package us.sunrisemorning.pixivbrower.spider;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Aop;

import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.downloader.HttpClientDownloader;
import us.codecraft.webmagic.proxy.Proxy;
import us.codecraft.webmagic.proxy.SimpleProxyProvider;
import us.sunrisemorning.pixivbrower.dao.ConfigService;
import us.sunrisemorning.pixivbrower.model.Config;

public class PixivSpider implements Runnable {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private ConfigService configService = Aop.get(ConfigService.class);

    public static final String URL = "https://www.pixiv.net/ajax/search/artworks/";

    private Spider spider = null;

    private SpiderCallback callback = null;
    private String keyword = null;
    private SpiderStatus status = new SpiderStatus();

    public PixivSpider(String keyword, SpiderCallback callback) {
        this.keyword = keyword;
        this.callback = callback;

        HttpClientDownloader downloader = new HttpClientDownloader();

        if (configService.getBooleanConfig(Config.USE_PROXY)) {
            downloader.setProxyProvider(SimpleProxyProvider.from(new Proxy(configService.getConfig(Config.PROXY_HOST), configService.getIntegerConfig(Config.PROXY_PORT))));
        }

        String pageUrl = URL + encodeKeyword(keyword) + "/?word=" + encodeKeyword(keyword) + "&order=date_d&mode=all&p=1&s_mode=s_tag&type=all&lang=zh";

        spider = Spider.create(new PixivProcessor(status));
        spider.setDownloader(downloader).addUrl(pageUrl).addPipeline(new DbPipeline(status));

        int threadAmount = configService.getIntegerConfig(Config.THREAD_AMOUNT);
        if (threadAmount > 1) {
            spider.thread(threadAmount);
        }
    }
    
    public void stop() {
        if (spider != null) {
            status.setStatus(-1);
            spider.stop();
        }
    }

    private String encodeKeyword(String keyword) {
        try {
            return URLEncoder.encode(keyword, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("PixivSpider encode keyword error.", e);
            return keyword;
        }
    }

    public String getKeyword() {
        return keyword;
    }

    public SpiderStatus getStatus() {
        return status;
    }

    @Override
    public void run() {
        if (spider != null) {
            spider.run();

            if (callback != null) {
                callback.callback();
            }
        }
    }
}
